<script setup>
import {ref, onMounted} from "vue"
import {queryStatistic, exportStatistic} from "@/api/eyeCare.js";
import edit from "./edit.vue"
import {ElMessage} from "element-plus";

import {
  USED_EYES_DURATION,
  SIT_TYPE,
  LIGHT_TYPE,
  WEAR_TYPE,
  ALLERGY,
  OUTDOOR_DURATION,
  GLASSES_TYPE,
  HABIT,
  OVERLAY_MEASURES
} from "@/utils/const.js";

const data = ref([])
const currentPage = ref(1)
const pageSize = ref(15)
const total = ref(0)
const editRef = ref(null)
const searchForm = ref("")

onMounted(() => {
  loadData(currentPage.value, pageSize.value, "")
})

const handleCurrentChange = (val) => {
  loadData(val, pageSize.value, "")
}

const loadData = async (page, pageSize, name) => {
  queryStatistic({
    page: page,
    pageSize: pageSize,
    name: name
  }).then(res => {
    res.data.records.forEach(item => {
      item.negativeFactor = JSON.parse(item.negativeFactor)
      item.prevention = JSON.parse(item.prevention)
    })
    data.value = res.data.records
    total.value = res.data.total
  })
}

const exportData = async () => {
  try {
    // 使用专门的导出API方法
    const response = await exportStatistic({
      name: "", // 搜索条件
    })

    // 获取文件名
    let filename = "视力统计.xlsx"

    // 创建并下载文件
    const url = window.URL.createObjectURL(response)
    const link = document.createElement("a")
    link.href = url
    link.setAttribute("download", filename)
    document.body.appendChild(link)
    link.click()
    link.remove()

    ElMessage.success("导出成功")
  } catch (error) {
    console.error("导出失败:", error)
    ElMessage.error("导出失败: " + (error.message || "未知错误"))
  }
}

const handleEdit = (row) => {
  editRef.value.showDialog(row)
}

const handleAdd = () => {
  editRef.value.showDialog()
}

const handleSearch = () => {
  currentPage.value = 1
  loadData(currentPage.value, pageSize.value, searchForm.value)
}

const refresh = () => {
  handleSearch()
}

</script>

<template>
  <div class="table-container">
    <div style="display: flex;align-items: center;margin-bottom: 12px;justify-content: space-between">
      <div>
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="primary" @click="exportData">导出</el-button>
      </div>
      <el-input size="small" style="width: 250px; margin-left: 16px;" v-model="searchForm" placeholder="请输入名称"
                clearable @clear="handleSearch" @keyup.enter="handleSearch">
        <template #append>
          <el-button @click="handleSearch">搜索</el-button>
        </template>
      </el-input>
    </div>

    <el-table
        :data="data"
        stripe
        border
        style="width: 100%">
      <el-table-column
          fixed
          prop="name"
          label="就诊人">
      </el-table-column>
      <el-table-column
          fixed
          width="100px"
          prop="birthday"
          label="生日">
      </el-table-column>
      <el-table-column
          fixed
          width="80px"
          prop="height"
          label="身高">
      </el-table-column>
      <el-table-column
          fixed
          width="70px"
          prop="sex"
          label="性别">
        <template #default="scope">
          <el-tag type="primary" v-if="scope.row.sex === 1">男</el-tag>
          <el-tag type="danger" v-else-if="scope.row.sex === 2">女</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          width="80px"
          prop="school"
          label="学校">
      </el-table-column>
      <el-table-column
          width="100px"
          prop="grade"
          label="学校级别">
      </el-table-column>
      <el-table-column
          width="80px"
          prop="clazz"
          label="班级">
      </el-table-column>
      <el-table-column
          width="100px"
          prop="attendDate"
          label="入学时间">
      </el-table-column>
      <el-table-column
          fixed
          width="100px"
          prop="healTime"
          label="就诊时间">
      </el-table-column>
      <el-table-column label="右眼">
        <el-table-column
            prop="rightVision"
            width="100px"
            label="裸眼视力">
        </el-table-column>
        <el-table-column
            prop="rightSphericalMirror"
            width="100px"
            label="散瞳/小瞳">
        </el-table-column>
        <el-table-column
            prop="rightCylinderMirror"
            label="散光">
        </el-table-column>
        <el-table-column
            prop="rightAxisPosition"
            label="轴位">
        </el-table-column>
        <el-table-column
            prop="rightOcularAxis"
            label="眼轴">
        </el-table-column>
        <el-table-column
            prop="rightHorizontalKeratometry"
            width="100px"
            label="平角膜曲率">
        </el-table-column>
        <el-table-column
            prop="rightVerticalKeratometry"
            width="100px"
            label="陡角膜曲率">
        </el-table-column>
      </el-table-column>

      <el-table-column label="左眼">
        <el-table-column
            prop="leftVision"
            width="100px"
            label="裸眼视力">
        </el-table-column>
        <el-table-column
            prop="leftSphericalMirror"
            width="100px"
            label="散瞳/小瞳">
        </el-table-column>
        <el-table-column
            prop="leftCylinderMirror"
            label="散光">
        </el-table-column>
        <el-table-column
            prop="leftAxisPosition"
            label="轴位">
        </el-table-column>
        <el-table-column
            prop="leftOcularAxis"
            label="眼轴">
        </el-table-column>
        <el-table-column
            prop="leftHorizontalKeratometry"
            width="100px"
            label="平角膜曲率">
        </el-table-column>
        <el-table-column
            prop="leftVerticalKeratometry"
            width="100px"
            label="陡角膜曲率">
        </el-table-column>
      </el-table-column>

      <el-table-column label="此前负面因素">
        <el-table-column
            prop="usedEyesDuration"
            width="120px"
            label="日均用眼时长">
          <template #default="scope">
            <el-tag v-if="!scope.row.negativeFactor || !scope.row.negativeFactor.usedEyesDuration">无</el-tag>
            <div v-else v-for="item in USED_EYES_DURATION">
              <el-tag type="danger" v-if="scope.row.negativeFactor.usedEyesDuration === item.key">{{
                  item.name
                }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            width="140px"
            prop="sitType"
            label="用眼姿势问题">
          <template #default="scope">
            <el-tag
                v-if="!scope.row.negativeFactor || !scope.row.negativeFactor.sitType || scope.row.negativeFactor.sitType.length === 0">
              无
            </el-tag>
            <div v-else v-for="item in SIT_TYPE">
              <el-tag type="danger" v-if="scope.row.negativeFactor.sitType.includes(item.key)">{{ item.name }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            width="180px"
            prop="lightType"
            label="光照情况">
          <template #default="scope">
            <el-tag
                v-if="!scope.row.negativeFactor || !scope.row.negativeFactor.lightType || scope.row.negativeFactor.lightType.length === 0">
              无
            </el-tag>
            <div v-else v-for="item in LIGHT_TYPE">
              <el-tag type="danger" v-if="scope.row.negativeFactor.lightType.includes(item.key)">{{
                  item.name
                }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            width="140px"
            prop="wearType"
            label="戴镜不正确">
          <template #default="scope">
            <el-tag
                v-if="!scope.row.negativeFactor || !scope.row.negativeFactor.wearType || scope.row.negativeFactor.wearType.length === 0">
              无
            </el-tag>
            <div v-else v-for="item in WEAR_TYPE">
              <el-tag type="danger" v-if="scope.row.negativeFactor.wearType.includes(item.key)">{{ item.name }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="ALLERGY"
            width="120px"
            label="过敏反应">
          <template #default="scope">
            <el-tag
                v-if="!scope.row.negativeFactor || !scope.row.negativeFactor.allergy || scope.row.negativeFactor.allergy.length === 0">
              无
            </el-tag>
            <div v-else v-for="item in ALLERGY">
              <el-tag type="danger" v-if="scope.row.negativeFactor.allergy.includes(item.key)">{{ item.name }}</el-tag>
            </div>
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column label="此前防控措施">
        <el-table-column
            prop="outdoorDuration"
            width="120px"
            label="日户外时长">
          <template #default="scope">
            <el-tag
                v-if="!scope.row.prevention || !scope.row.prevention.outdoorDuration || scope.row.prevention.outdoorDuration.length === 0">
              无
            </el-tag>
            <div v-else v-for="item in OUTDOOR_DURATION">
              <el-tag type="danger" v-if="scope.row.prevention.outdoorDuration.includes(item.key)">{{
                  item.name
                }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="glassesType"
            width="120px"
            label="戴镜">
          <template #default="scope">
            <el-tag
                v-if="!scope.row.prevention || !scope.row.prevention.glassesType || scope.row.prevention.glassesType.length === 0">
              无
            </el-tag>
            <div v-else v-for="item in GLASSES_TYPE">
              <el-tag type="danger" v-if="scope.row.prevention.glassesType.includes(item.key)">{{ item.name }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="habit"
            width="120px"
            label="戴镜习惯">
          <template #default="scope">
            <el-tag
                v-if="!scope.row.prevention || !scope.row.prevention.habit || scope.row.prevention.habit.length === 0">无
            </el-tag>
            <div v-else v-for="item in HABIT">
              <el-tag type="danger" v-if="scope.row.prevention.habit.includes(item.key)">{{ item.name }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="overlayMeasures"
            width="120px"
            label="叠加措施">
          <template #default="scope">
            <el-tag
                v-if="!scope.row.prevention || !scope.row.prevention.overlayMeasures || scope.row.prevention.overlayMeasures.length === 0">
              无
            </el-tag>
            <div v-else v-for="item in OVERLAY_MEASURES">
              <el-tag type="danger" v-if="scope.row.prevention.overlayMeasures.includes(item.key)">{{
                  item.name
                }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="笔记" prop="note">
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="100px">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :background="true"
        layout="total, prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
    />

    <edit ref="editRef" @onConfirm="refresh"></edit>
  </div>

</template>

<style scoped lang="scss">
.table-container {
  padding: 16px;

  .el-pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 8px;
  }
}
</style>